package li.controller;

import li.dto.Cart;
import li.dto.CartItem;
import li.dto.Sku;
import li.dto.TbUser;
import li.service.CartService;

import li.util.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/cart")
public class CartCtrl {
    @Autowired
    CartService cs;

    @RequestMapping("/addToCart")
    public String addToCart(Sku s, HttpSession session){
        TbUser user = (TbUser)session.getAttribute("user");
        if(user==null){
            return "global-exception";
        }
        cs.addToCart(s,user);
        return "添加成功";
    }

    @RequestMapping("/selectCart")
    public Cart findUserCart(HttpSession session){
        TbUser user = (TbUser)session.getAttribute("user");
        if(user==null){
            return null;
        }
        return cs.findCart(user);
    }

    @RequestMapping("/updateCount")
    public String changeItemNum(Integer pid,Integer pcount,HttpSession session){
        TbUser user = (TbUser) session.getAttribute("user");
        if (user==null) {
            return "没有登录";
        }
        return cs.changeItemNum(pid,pcount,user);
    }

    @RequestMapping("/deleteItem")
    public String deleteItem(Integer pid,HttpSession session){
        TbUser user = (TbUser) session.getAttribute("user");
        Map<Integer, CartItem> cart = Cache.CART.get(user.getId());
        cart.remove(pid);
        return "success";
    }
}
